﻿using System;
using Tao.Sdl;

namespace HDM.NexusEngine.Input
{
    public class XboxController : IDisposable
    {
        private readonly IntPtr _joystick;

        public ControlStick LeftControlStick { get; private set; }
        public ControlStick RightControlStick { get; private set; }
        public ControlButton ButtonA { get; private set; }
        public ControlButton ButtonB { get; private set; }
        public ControlButton ButtonX { get; private set; }
        public ControlButton ButtonY { get; private set; }
        public ControlButton ButtonLB { get; private set; }
        public ControlButton ButtonRB { get; private set; }
        public ControlButton ButtonBack { get; private set; }
        public ControlButton ButtonStart { get; private set; }
        public ControlButton ButtonL3 { get; private set; }
        public ControlButton ButtonR3 { get; private set; }
        public ControlTrigger LefTrigger { get; private set; }
        public ControlTrigger RighTrigger { get; private set; }
        public DPad Dpad { get; private set; }

        public XboxController(int player)
        {
            _joystick = Sdl.SDL_JoystickOpen(player);
            LeftControlStick = new ControlStick(_joystick, 0, 1);
            RightControlStick = new ControlStick(_joystick, 4, 3);
            ButtonA = new ControlButton(_joystick, 0);
            ButtonB = new ControlButton(_joystick, 1);
            ButtonX = new ControlButton(_joystick, 2);
            ButtonY = new ControlButton(_joystick, 3);
            ButtonLB = new ControlButton(_joystick, 4);
            ButtonRB = new ControlButton(_joystick, 5);
            ButtonBack = new ControlButton(_joystick, 6);
            ButtonStart = new ControlButton(_joystick, 7);
            ButtonL3 = new ControlButton(_joystick, 8);
            ButtonR3 = new ControlButton(_joystick, 9);
            LefTrigger = new ControlTrigger(_joystick, 2, true);
            RighTrigger = new ControlTrigger(_joystick, 2, false);
            Dpad = new DPad(_joystick, 0);
        }

        public void Update()
        {
            LeftControlStick.Update();
            RightControlStick.Update();
            ButtonA.Update();
            ButtonB.Update();
            ButtonX.Update();
            ButtonY.Update();
            ButtonLB.Update();
            ButtonRB.Update();
            ButtonBack.Update();
            ButtonStart.Update();
            ButtonL3.Update();
            ButtonR3.Update();
            LefTrigger.Update();
            RighTrigger.Update();
            Dpad.Update();
        }

        public void Dispose()
        {
            Sdl.SDL_JoystickClose(_joystick);
        }
    }
}